package diamonds;

import org.apache.axis.client.Service;
import org.apache.axis.client.Call;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.faces.event.ActionEvent;
import javax.xml.namespace.QName;

public class LoginBean {
		private static final Log log = LogFactory.getLog(LoginBean.class);

    private ControllerBean controller;

    public ControllerBean getController() {
			return controller;
		}

		public void setController(ControllerBean controllerBean) {
			this.controller = controllerBean;
		}

		public void doLogin(ActionEvent event) {
    	UserBean user = controller.getUser();

    	try {
	      String endpoint =
	              "http://www.ebi.ac.uk:80/microarray-srv/EP/cgi-bin/epws_soap.pl";

	      Service service = new Service();
	      Call call = (Call)service.createCall();

	      call.setTargetEndpointAddress(new java.net.URL(endpoint));
	      call.setOperationName(new QName("http://www.ebi.ac.uk/EP/WS/SOAP", "epLogin"));
	      call.addParameter("username", org.apache.axis.Constants.XSD_STRING, javax.xml.rpc.ParameterMode.IN);
	      call.addParameter("password", org.apache.axis.Constants.XSD_STRING, javax.xml.rpc.ParameterMode.IN);
	      call.setReturnType(org.apache.axis.Constants.XSD_STRING);

	      String sessionId = (String) call.invoke(new Object[]{user.getName(), user.getPassword()});

	      log.info("Sent '" + user.getName() + "/" + user.getPassword() + "', got '" + sessionId + "'");
	      user.setSessionId(sessionId);
	      user.setAuthError(null);
	      controller.getLoginStatus().setValue(user.getName());
	      controller.getLoginDialog().setShow(false);
	      controller.getStatusText().setValue("Logged in successfully as " + user.getName());
		  } catch(java.rmi.RemoteException x) {
		      log.error("Got SOAP error " + x.getMessage());
		      user.setAuthError(x.getMessage());
		  } catch (Exception x) {
		      log.error("Got exception" + x.getMessage());
		      x.printStackTrace();
		  }
		}
}
